<template>
	<view class="field-switch field-form-item">
		<u-form-item :label="label" :required="required" :prop="prop">
			<u-switch 
				:value="value"
				:size="size"
				:active-color="activeColor"
				:inactive-color="inactiveColor"
				:disabled="disabled"
				@input="onChange"
			/>
		</u-form-item>
	</view>
</template>

<script>
	import style from 'uni.scss';
	import { validateWidget } from '@/utils/validate.js';

	export default {
		name: 'fieldSwitch',
		props: {
			label: {
				type: String
			},
			value: {
				type: Boolean,
				default: false
			},
			prop: {
				type: String
			},
			size: {
				type: [String, Number],
				default: 40
			},
			activeColor: {
				type: String,
				default: style.primary_color
			},
			inactiveColor: {
				type: String,
				default: '#E8E8E8'
			},
			required: {
				type: Boolean,
				default: false
			},
			rules: {
				type: Array
			},
			disabled: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				dirty: false,
				errorMessage: ''
			}
		},
		methods: {
			onChange(val) {
				this.$emit('input', val);
				this.$emit('change', val);
				this.dirty = true;
			},
			setDirty(dirty) {
				this.dirty = dirty;
			},
			getDirty() {
				return this.dirty;
			},
			validateWidget() {
				return new Promise((resolve, reject) => {
					validateWidget(this.rules, this.value).then(res => {
						this.errorMessage = '';
						resolve();
					}).catch(e => {
						this.errorMessage = e;
						resolve(e)
					});
				});
			}
		}
	}
</script>

<style scoped>
.field-switch ::v-deep .fild-body view:first {
	flex: 0!important;
}
</style>